package com.hnichr.ump.business.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.hnichr.ump.business.Constant;
import com.hnichr.ump.common.doc.entity.Order;
import com.hnichr.ump.common.doc.service.OrderService;
import com.hnichr.ump.common.util.GenerateUtils;
import com.mxpioframework.common.CommonConstant;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.filestorage.entity.MxpioFileInfo;
import com.mxpioframework.filestorage.service.FileStorageService;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import cn.hutool.core.map.MapUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/doc/order/v1/")
@Tag(name = "OrderController", description = "文印商城订单接口")
@Slf4j
public class OrderController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private FileStorageService fileStorageService;

	@Value("${minio.resUrl}")
	private String restUrl;

	@GetMapping("page")
	@Operation(summary = "订单列表", description = "获取订单列表", method = "GET")
	public Result<Page<Order>> page(@Parameter(description = "查询参数") Criteria criteria,
			@Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) {
		Pageable page = PageRequest.of(pageNo - 1, pageSize);
		criteria.addCriterion("validFlag", Operator.EQ, Constant.STATUS_VALID);
		criteria.addOrder(new com.mxpioframework.jpa.query.Order("createTime", true));
		Page<Order> list = orderService.listPage(Order.class, page, criteria);
		return Result.OK(list);
	}

	@GetMapping("list")
	@Operation(summary = "订单列表", description = "获取订单列表（无分页）", method = "GET")
	public Result<List<Order>> list(@Parameter(description = "查询参数") Criteria criteria) {
		List<Order> list = orderService.list(Order.class, criteria);
		return Result.OK(list);
	}

	@PostMapping("distribute")
	@Operation(summary = "分配订单", description = "按群组分配订单", method = "POST")
	public Result<Void> distribute(@RequestBody Map<String, Object> param) {
		orderService.distribute(MapUtil.getStr(param, "orderNo"), MapUtil.getStr(param, "groupId"));
		return Result.OK();
	}

	@PostMapping("upload")
	@Operation(summary = "上传文件", description = "上传文件", method = "POST")
	public Result<Void> upload(@RequestParam("file") MultipartFile file, @RequestParam("orderNo") String orderNo,
			@RequestParam("field") String field) {
		orderService.upload(file, orderNo, field);
		return Result.OK();
	}

	@PutMapping("edit")
	@Operation(summary = "编辑订单", description = "编辑订单", method = "PUT")
	public Result<Order> edit(@RequestBody Order order) {
		orderService.update(order);
		return Result.OK(order);
	}

	@PostMapping("add")
	@Operation(summary = "新增订单", description = "新增订单", method = "POST")
	public Result<Order> add(@RequestBody Order order) {
		order.setOrderNo(GenerateUtils.getOrderNo());// 设置订单状态
		order.setStatus(Constant.DOC_STATUS_50);
		order.setValidFlag(Constant.STATUS_VALID);
		orderService.save(order);
		return Result.OK(order);
	}

	@DeleteMapping("remove/{id}")
	@Operation(summary = "根据id删除订单", description = "根据id删除订单", method = "DELETE")
	public Result<Order> remove(@PathVariable(name = "id", required = true) String id) {
		Order order = orderService.getById(Order.class, id);
		order.setDesignerId(null);
		order.setDesignerName(null);
		order.setCheckId(null);
		order.setCheckName(null);
		order.setAfterWorkId(null);
		order.setAfterWorkName(null);
		order.setStatus(Constant.DOC_STATUS_10);
		orderService.update(order);
		return Result.OK();
	}

	@PostMapping("updateStatus")
	@Operation(summary = "更新订单状态", description = "更新订单状态", method = "POST")
	public Result<Void> updateStatus(@RequestBody Map<String, String> param) {
		try {
			orderService.updateStatus(MapUtil.getStr(param, "type"), MapUtil.getStr(param, "orderNo"),
					MapUtil.getStr(param, "status"));
			return Result.OK();
		} catch (Exception e) {
			Result<Void> result = new Result<>();
			result.setSuccess(false);
			result.setCode(CommonConstant.HTTP_OK);
			result.setMessage(e.getMessage());
			return result;
		}
	}

	/**
	 * 获取订单预览图
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getPreviewImage")
	@Operation(summary = "获取预览图", description = "获取预览图", method = "GET")
	public Result<String> getPreviewImage(@RequestParam("fileNo") String fileNo, HttpServletResponse response) {
		if (StringUtils.isBlank(fileNo)) {
			return Result.error("fileNo不能为空！");
		}
		try {
			MxpioFileInfo fileInfo = fileStorageService.get(fileNo);
			return Result.OK(restUrl + "/" + fileInfo.getAbsolutePath());
		} catch (Exception e) {
			log.error("获取预览图失败：", e);
			return Result.error("获取预览图失败");
		}
	}
}
